package com.effectivejava;

import java.io.*;

/**
 * @ClassName: Nineth
 * @Description: 第九条，27页，try-with-resource优于try-finally
 * @author: li
 * @Date: 2021/8/20 4:38 下午
 */
public class Nineth {
    static int BUFFER_SIZE = 16;
    static String firstLineOfFile(String path) throws FileNotFoundException {
        BufferedReader bufferedReader = new BufferedReader(new FileReader(path));
        String line = "";
        try {
            line =  bufferedReader.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return line;
    }

    static String firstLineOfFile1(String path)  {
        String  line = "";
        /**
         * try-with-resource会自动在结束时，调用close关闭资源，同时如果readline和（不可见）close都出现异常，会禁用后面的异常，保留第一个异常。
         * try-with-resource 相对于 try - finally 更加简洁。
         */
        try(BufferedReader bufferedReader = new BufferedReader(new FileReader(path))){
            line =  bufferedReader.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return line;

    }

    static void copy(String src, String dst) throws FileNotFoundException {
        InputStream in = new FileInputStream(src);
        try {
            OutputStream out = new FileOutputStream(dst);
            try {
                byte[] buf = new byte[BUFFER_SIZE];
                int n;
                while ((n = in.read(buf)) >=0){
                    out.write(buf,0,n);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    out.close();
                } catch (IOException e) {
                    // 如果这个异常抛出，则前一个抛出的异常就会丢失
                    e.printStackTrace();
                }
            }

        }  finally {
            try {
                in.close();
            } catch (IOException e) {
                // 如果这个异常抛出，则前一个抛出的异常就会丢失

                e.printStackTrace();
            }
        }
    }

    static void copy1(String src, String dst){
        try (InputStream in = new FileInputStream(src);OutputStream out = new FileOutputStream(dst)){
            byte[] buf = new byte[BUFFER_SIZE];
            int n;
            while ((n = in.read(buf)) >=0){
                out.write(buf);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
